package com.toddsoft.util;

/**
 * class to emulate key repeats
 */
public abstract class Repeater extends Thread {
    private boolean go = false;
    
    public Repeater() {
        this.start();         
    }
    
    public void run() {

        theLoop:
        while (true) {
            /* wait to run */
            try {
                synchronized (this) {
                    this.wait();
                }
            } catch (InterruptedException ie) {
                interrupted();
                continue theLoop;
            }

            long sleepTime = getFirstPauseMs();
            while (go) {
                /* do whatever this thread should */
                repeat();

                /* wait for appropriate time */
                try {
                    sleep(sleepTime);
                    sleepTime = this.getRepeatMs();
                } catch (InterruptedException ie) {
                    interrupted();
                }
            }
        }         
    }
    
    public void startRepeater() {
        if (!go) {
            go = true;
            synchronized (this) {
                //notify it if it's waiting
                this.notify();
            }         
        }
    }
    
    public void stopRepeater() {
        if (go) {
            go = false;         
            //interrupt the sleep, so it can return to a waiting state
            this.interrupt();
        }
    }
    
    public abstract void repeat();
    
    /**
     * @return int
     */
    public abstract long getRepeatMs();

    /**
     * @return int
     */
    public long getFirstPauseMs() {
        return getRepeatMs();
    }
}

